<template>
  <el-form :model="localForm" label-width="120px">
    <el-form-item label="端口" prop="port">
      <el-input v-model.number="localForm.port" placeholder="请输入端口" type="number" @input="syncToParent" />
    </el-form-item>
    <el-form-item label="用户名" prop="username">
      <el-input v-model="localForm.username" placeholder="请输入用户名" :disabled="isUsernameDisabled" @input="syncToParent" />
    </el-form-item>
    <el-form-item label="认证方式" prop="authType">
      <el-radio-group v-model="localForm.authType" @change="handleAuthTypeChange">
        <el-radio label="password">密码认证</el-radio>
        <el-radio label="cert">身份认证</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item 
      label="主机密码" 
      prop="password"
      v-if="localForm.authType === 'password'"
    >
      <el-input 
        v-model="localForm.password" 
        type="password" 
        placeholder="请输入主机密码" 
        show-password
        @input="syncToParent"
      />
    </el-form-item>
    <el-form-item 
      label="主机身份" 
      v-if="localForm.authType === 'cert'" 
      prop="hostIdentityId"
    >
      <el-select 
        v-model="localForm.hostIdentityId" 
        filterable 
        placeholder="请选择主机身份"
        style="width: 100%"
        :loading="identityLoading"
        @change="handleIdentityChange"
      >
        <el-option
          v-for="item in identityList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="连接超时时间" prop="connectTimeout">
      <el-input v-model.number="localForm.connectTimeout" placeholder="请输入连接超时时间" type="number" @input="syncToParent" />
      <span style="margin-left: 8px;">ms</span>
    </el-form-item>
    <el-form-item label="SSH输出编码" prop="charset">
      <el-input v-model="localForm.charset" placeholder="SSH输出编码" @input="syncToParent" />
    </el-form-item>
    <el-form-item label="文件名称编码" prop="fileNameCharset">
      <el-input v-model="localForm.fileNameCharset" placeholder="文件名称编码" @input="syncToParent" />
    </el-form-item>
    <el-form-item label="文件内容编码" prop="fileContentCharset">
      <el-input v-model="localForm.fileContentCharset" placeholder="文件内容编码" @input="syncToParent" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleTestSsh">测试连接</el-button>  
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue';
import { getIdentityList,testHostSsh } from "@/api/os/host";
const { proxy } = getCurrentInstance()
const props = defineProps({
  modelValue: Object, // 接收弹框的form.ssh
  isEdit: Boolean,    // 新增/编辑标记
});
const emit = defineEmits(['update:modelValue']);

// 初始化表单数据，设置固定默认值
const initFormData = () => {
  const modelValue = props.modelValue || {};
  return {
    port: modelValue.port || 22,
    username: modelValue.username || '',
    authType: modelValue.authType || 'password',
    password: modelValue.password || '',
    hostIdentityId: modelValue.hostIdentityId || '',
    connectTimeout: modelValue.connectTimeout || 5000,
    charset: modelValue.charset || 'utf-8', // 固定默认值
    fileNameCharset: modelValue.fileNameCharset || 'utf-8', // 固定默认值
    fileContentCharset: modelValue.fileContentCharset || 'utf-8', // 固定默认值
    useOriginalPwd: modelValue.useOriginalPwd || false,
    originalUsername: modelValue.originalUsername || ''
  };
};

const localForm = ref(initFormData());

// 身份列表相关状态
const identityList = ref([]);
const identityLoading = ref(false);

// 同步本地数据到父组件
const syncToParent = () => {
  // 确保编码字段有值
  const dataToEmit = {
    ...localForm.value,
    charset: localForm.value.charset || 'utf-8',
    fileNameCharset: localForm.value.fileNameCharset || 'utf-8',
    fileContentCharset: localForm.value.fileContentCharset || 'utf-8'
  };
  
  // 移除临时字段
  delete dataToEmit.originalUsername;
  
  emit('update:modelValue', dataToEmit);
};

// 计算用户名输入框是否禁用
const isUsernameDisabled = computed(() => {
  return localForm.value.authType === 'cert' && localForm.value.hostIdentityId;
});

// 监听props.modelValue变化（如编辑时初始化）
watch(() => props.modelValue, (val) => {
  if (val) {
    // 确保编码字段有值，如果没有则使用默认值
    localForm.value = { 
      ...localForm.value, // 保留当前值
      ...val, // 覆盖来自父组件的值
      charset: val.charset || 'utf-8',
      fileNameCharset: val.fileNameCharset || 'utf-8',
      fileContentCharset: val.fileContentCharset || 'utf-8'
    };
  }
}, { deep: true, immediate: true });

// 认证方式变化处理
const handleAuthTypeChange = (value) => {
  if (value === 'password') {
    // 切换到密码认证时，清除身份字段并恢复用户名可编辑
    localForm.value.hostIdentityId = '';
    localForm.value.username = localForm.value.originalUsername || '';
  } else if (value === 'cert') {
    // 切换到身份认证时，保存原始用户名（如果有）
    if (localForm.value.username && !localForm.value.originalUsername) {
      localForm.value.originalUsername = localForm.value.username;
    }
    // 如果已经选择了身份，则自动填充用户名
    if (localForm.value.hostIdentityId) {
      fillUsernameFromIdentity();
    }
  }
  syncToParent();
};

// 身份选择变化处理
const handleIdentityChange = (hostIdentityId) => {
  if (hostIdentityId) {
    fillUsernameFromIdentity();
  } else {
    // 清空选择时，清空用户名
    localForm.value.username = '';
  }
  syncToParent();
};

// 从选择的身份中填充用户名
const fillUsernameFromIdentity = () => {
  const selectedIdentity = identityList.value.find(
    item => item.id === localForm.value.hostIdentityId
  );
  if (selectedIdentity && selectedIdentity.username) {
    localForm.value.username = selectedIdentity.username;
    syncToParent();
  }
};

// 加载身份列表
const loadIdentityList = async () => {
  try {
    identityLoading.value = true;
    const res = await getIdentityList();
    identityList.value = res.data || [];
    
    // 如果是编辑模式且已经选择了身份，自动填充用户名
    if (props.isEdit && localForm.value.authType === 'cert' && localForm.value.hostIdentityId) {
      fillUsernameFromIdentity();
    }
  } catch (error) {
    console.error('加载身份列表失败', error);
    identityList.value = [];
  } finally {
    identityLoading.value = false;
  }
};

// 测试连接方法
const handleTestSsh = async () => {
    // 校验表单（如有需要可加校验）
    // await formRef.value.validate();

    // 提交当前SSH表单数据
    const res = await testHostSsh(localForm.value);
    if (res.code === 200) {
      // 成功提示
      proxy.$modal.msgSuccess(`连接测试成功`);
      return;
    } else {
     proxy.$modal.msgSuccess(res.msg || `连接测试失败`);
      return;
    }
  
};

// 组件挂载时加载身份列表
onMounted(() => {
  loadIdentityList();
  // 初始同步一次
  syncToParent();
});
</script>